package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import utils.AirTransportRepositoryManager;

public class LoginController extends AbstractController {

	private static final String MAIN_VIEW = "redirect:main.html";
	
	
	private AirTransportRepositoryManager repositoryManager;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
		ModelAndView mav = new ModelAndView();
		
		if (request.isRequestedSessionIdFromCookie() == false ||
				request.isRequestedSessionIdValid() == false) {
			
			mav.addObject("error_message", "Cookies must be enabled !");
		}
		
		String userParam = request.getParameter("user");
		String passParam = request.getParameter("pass");
		
		if (userParam == null || passParam == null) {
			return mav;
		}
		
		HttpSession session = request.getSession();
		
		User user = (User) session.getAttribute("user");
		
		if (user == null) {
			return mav;
		}
		
		user.setUsername(userParam);
		user.setPassword(passParam);
		
		if ( user.isLoggedIn() == true ) {
			mav.addObject("error_message", "Already logged in with username:<i> " + userParam +  "</i> !");
			return mav;
		}
		
		if ( repositoryManager.loginUser(user) == true ) {
			mav = new ModelAndView(MAIN_VIEW);
		}

		return mav;
	}

	public AirTransportRepositoryManager getRepositoryManager() {
		return repositoryManager;
	}

	public void setRepositoryManager(AirTransportRepositoryManager repositoryManager) {
		this.repositoryManager = repositoryManager;
	}


}
